package com.jerry.selector.Impl;

import com.jerry.BO.ServerInfo;
import com.jerry.selector.ServerSelector;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
@Slf4j
public class DefaultServerSelector implements ServerSelector {
    @Override
    public List<ServerInfo> select(List<ServerInfo> aliveServers, int count) {
        log.info("{}",aliveServers.size());
        log.info("{}",count);
        if (aliveServers.size() < count) {
            throw new RuntimeException("存活数量小于分片存储数量");
        }
        int[] idxArray = new int[aliveServers.size()];
        for (int i = 0; i < idxArray.length; i++) {
            idxArray[i] = i;
        }
// 洗牌法打乱
        for (int i = 0; i < count; i++) {
            int randomIndex = (int) (Math.random() * aliveServers.size());
            int tmp = idxArray[randomIndex];
            idxArray[randomIndex] = idxArray[i];
            idxArray[i] = tmp;
        }
        List<ServerInfo> selectedServers = new ArrayList<>();
        for (int i = 0; i < count; i++) {
            selectedServers.add(aliveServers.get(idxArray[i]));
        }
        return selectedServers;
    }
}
